import time

import coin.exchange.base.kr_ws.ws_client_base as wscb
import coin.exchange.bithumb.kr_ws.ws_parser as wsp
from coin.exchange.bithumb.kr_ws.ws_parser import BithumbWSParserManager
from coin.exchange.bithumb.kr_rest.product import BithumbProduct
from coin.exchange.base.kr_ws.ws_parser_base import (WsFeedPrinter, WsFeedArchiver)


class BithumbWsRequest(wscb.WebsocketRequestBase):
  @staticmethod
  def FromSingleProduct(product):
    return BithumbWsRequest(product)

  def __init__(self, product=None):
    self.product = BithumbProduct.FromAny(product)


class BithumbWSClient(wscb.WebsocketClientBase):
  RequestType = BithumbWsRequest

  def __init__(self, request, feed_handler):
    wscb.WebsocketClientBase.__init__(self,
                                      url="wss://wss.bithumb.com/public",
                                      request=request,
                                      handler=BithumbWSParserManager(feed_handler))

  def _connect_impl(self):
    # only gives book
    # {'service': 'orderbook', 'currency': 'BTC'}
    # only gives trade
    # {'service': 'transaction', 'currency': 'BTC'}
    # book + trade + ticker
    # {'currency': 'BTC', 'tickDuration': '24H'}
    # all info
    # {'service': 'ticker', 'tickDuration': '24H'}
    sub_params = {'currency': self._request.product.native_symbol, 'tickDuration': '24H'}
    self._send_as_json(sub_params)

  def _disconnect_impl(self):
    pass

  def _heartbeat_impl(self):
    pass


if __name__ == "__main__":
  request = BithumbWsRequest("ETH-KRW")
  wsClient = BithumbWSClient(request, WsFeedPrinter(verbose=True))
  wsClient.start()
  wsClient.printInfo()
  while (wsClient.getRecvMsgCount() < 100):
    print("RecvMsgCount =", "%i" % wsClient.getRecvMsgCount())
    time.sleep(1)
  wsClient.stop()
